package com.sh.d1.gameserver;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.sh.util.NacosConfigUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.InputStream;
import java.util.Properties;

/**
 * MySQL 会话工厂
 */
public class MySqlSessionFactory {
    /**
     * 日志对象
     */
    static private final Logger LOGGER = LoggerFactory.getLogger(MySqlSessionFactory.class);

    /**
     * SQL 会话工厂
     */
    static private SqlSessionFactory _sqlSessionFactory;

    /**
     * 私有化类默认构造器
     */
    private MySqlSessionFactory() {
    }

    /**
     * 初始化
     */
    static public void init() {
        try {
            InputStream ins = Resources.getResourceAsStream("MyBatisConfig.xml");

            Properties prop = new Properties();
            prop.setProperty("MYSQL_SERVER_HOST", NacosConfigUtil.getValueByKey("MYSQL_SERVER_HOST"));
            prop.setProperty("MYSQL_SERVER_PORT", NacosConfigUtil.getValueByKey("MYSQL_SERVER_PORT"));
            prop.setProperty("MYSQL_DB", NacosConfigUtil.getValueByKey("MYSQL_DB"));
            prop.setProperty("MYSQL_USER", NacosConfigUtil.getValueByKey("MYSQL_USER"));
            prop.setProperty("MYSQL_PASSWORD", NacosConfigUtil.getValueByKey("MYSQL_PASSWORD"));

            _sqlSessionFactory = new SqlSessionFactoryBuilder().build(ins, prop);

            // 创建临时会话
            SqlSession tempSession = openSession();

            // 测试数据库连接
            tempSession.getConnection()
                .createStatement()
                .execute("SELECT -1");

            // 关闭临时会话
            tempSession.close();

            LOGGER.info("MySql 数据库连接成功!");
        } catch (Exception ex) {
            // 抛出运行时异常
            throw new RuntimeException(ex);
        }
    }

    /**
     * 开启 MySql 会话
     *
     * @return MySql 会话
     */
    static public SqlSession openSession() {
        if (null == _sqlSessionFactory) {
            throw new RuntimeException("_sqlSessionFactory 尚未初始化");
        }

        return _sqlSessionFactory.openSession(true);
    }
}
